<template>
  <el-dialog custom-class="ins-dialog" :destroy-on-close="true" :close-on-press-escape="false" :close-on-click-modal="false" append-to-body :title="title" :visible.sync="open" width="1000px" :before-close="close">
    <div slot="title" style="display: flex;justify-content: space-between;padding-right: 35px;">
      <span>{{ title }}</span>
      <span>南京新闻</span>
    </div>

    <el-steps :active="active" simple style="margin-bottom: 15px;">
      <el-step title="填写" icon="el-icon-edit" />
      <el-step title="打印" icon="el-icon-upload" />
      <el-step title="盖章上传" icon="el-icon-picture" />
    </el-steps>

    <el-form v-if="active == 1" ref="form" :rules="rules" :model="form" label-width="120px">
      <el-form-item label="作品标题" prop="news_title">
        <el-input v-model="form.news_title" />
      </el-form-item>

      <el-form-item label="体裁" prop="genre">
        <el-select v-model="form.genre" allow-create clearable filterable placeholder="请选择体裁">
          <el-option label="特写报道" value="特写报道" />
          <el-option label="采访报道" value="采访报道" />
          <el-option label="新闻分析" value="新闻分析" />
          <el-option label="专访" value="专访" />
          <el-option label="社论" value="社论" />
          <el-option label="其他" value="其他" />
        </el-select>
      </el-form-item>

      <el-form-item label="作品链接">
        <el-row>
          <el-col :xs="20" :sm="20" :md="20" :lg="20" :xl="20">
            <el-input v-model="form.news_link" />
          </el-col>
          <el-col :xs="4" :sm="4" :md="4" :lg="4" :xl="4" style="text-align: right;">
            <el-tooltip class="item" effect="dark" content="没有作品链接，" placement="top-start">
              <div slot="content" style="text-align: center;">没有作品链接？<br>可以通过附件上传作品信息</div>
              <span style="color:#409EFF;"> 没有链接？</span>
            </el-tooltip>
          </el-col>

        </el-row>
      </el-form-item>

      <el-form-item label="附件上传">
        <el-upload
          ref="upload"
          multiple
          class="upload-demo"
          :action="imageAction"
          :headers="{ 'Authorization': 'Bearer ' + authToken, }"
          :on-preview="handlePreview"
          :on-remove="handleRemove"
          :file-list="fileList"
          :on-success="handleSuccess"
          :before-upload="beforeUpload"
        >
          <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
          <!--          <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>-->
          <div slot="tip" class="el-upload__tip">只能上传图片、音视频、PDF文件，且不超过5Mb</div>
        </el-upload>
      </el-form-item>

      <el-form-item label="刊指平台" prop="publication_json">
        <el-row v-for="(item,index) in form.publication_json" :key="index" type="flex" style="justify-content: space-between;align-items: center;margin-bottom: 5px;">
          <el-col :xs="7" :sm="7" :md="7" :lg="7" :xl="7">
            <el-select v-model="item.publication_platform" allow-create clearable filterable style="width: 100%;" placeholder="请选择刊指平台">

              <template v-for="(item,index) in platformList">
                <el-option :key="index" :label="item.name" :value="item.name" />
              </template>

              <el-option label="其他" value="其他" />
            </el-select>
          </el-col>

          <el-col :xs="7" :sm="7" :md="7" :lg="7" :xl="7">
            <el-input v-model="item.publication_date" placeholder="请输入刊指时间" />
          </el-col>
          <el-col :xs="7" :sm="7" :md="7" :lg="7" :xl="7">
            <el-input v-model="item.publication_layout" placeholder="请输入刊指版面" />
          </el-col>
          <i class="el-icon el-icon-delete" @click="delPublication(index)" />
        </el-row>

        <el-button type="primary" plain style="width: 100%;margin-top: 10px;" @click="addPublication">+添加刊指平台</el-button>
      </el-form-item>

      <el-form-item label="作者姓名" prop="author_name">
        <el-input v-model="form.author_name" />
      </el-form-item>

      <el-form-item label="编者">
        <el-input v-model="form.editor" />
      </el-form-item>

      <el-form-item label="署名排序" prop="byline_order">
        <el-input v-model="form.byline_order" />
      </el-form-item>

      <el-form-item label="作品简介" prop="work_summary">
        <el-input
          v-model="form.work_summary"
          type="textarea"
          :autosize="{ minRows: 4, maxRows: 6}"
          placeholder="请输入作品简介"
          maxlength="800"
          show-word-limit
        />
      </el-form-item>

      <el-form-item label="填报人" prop="reporter">
        <el-input v-model="form.reporter" />
      </el-form-item>

      <el-form-item label="填报人手机号" prop="reporter_phone">
        <el-input v-model="form.reporter_phone" />
      </el-form-item>

      <!--      <el-form-item label="作品简介">-->
      <!--        <vue-ueditor-wrap-->
      <!--          v-model="content"-->
      <!--          editor-id="editor"-->
      <!--          :config="editorConfig"-->
      <!--          :editor-dependencies="['ueditor.config.js','ueditor.all.js']"-->
      <!--          style="height:500px;"-->
      <!--        />-->
      <!--      </el-form-item>-->

    </el-form>

    <el-alert
      v-if="active== 2"
      title="请打印此表，经营所在单位盖章后上传此表"
      type="error"
      close-text="知道了"
    />
    <InstitutionPrint v-if="active== 2" :form="printForm" :print-open="true" />

    <el-form v-if="active == 3" ref="form1" :rules="rules" :model="form" label-width="120px" style="margin-top: 20px">
      <el-upload
        ref="upload1"
        drag
        multiple
        class="upload-demo"
        :action="imageAction"
        :headers="{ 'Authorization': 'Bearer ' + authToken, }"
        :on-preview="handlePreview"
        :on-remove="handleRemove"
        :file-list="fileList1"
        :on-success="handleSuccess1"
        :before-upload="beforeUpload"
        style="display: flex;flex-direction: column;justify-content: center;align-items: center;"
      >
        <i class="el-icon-upload" />

        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>

      </el-upload>
    </el-form>

    <div slot="footer" class="dialog-footer">
      <el-button v-if="active > 1" style="margin-top: 12px;" @click="prev">{{ pervBtnName }}</el-button>
      <el-button v-if="active > 1 && active < 3" style="margin-top: 12px;" @click="next">{{ nextBtnName }}</el-button>
      <el-button v-if="active == 1" type="primary" size="medium" @click="submitForm('form')">{{ btnLabel }}</el-button>
      <el-button v-if="active == 3" type="danger" size="medium" @click="submitForm('form1',true)">申报</el-button>

      <!--      <el-button type="primary" @click="dialogFormVisible = false">确 定</el-button>-->
    </div>

  </el-dialog>
</template>

<script>
import VueUeditorWrap from 'vue-ueditor-wrap'
import { editGoods, postGoods } from '@/api/externalGoods'
import { newsDeclareAdd, newsDeclareUpdate, platformList } from '@/api/newsDeclare'
import InstitutionPrint from './Print'

export default {
  name: 'InstitutionAddEdit',
  components: {
    VueUeditorWrap,
    InstitutionPrint
  },
  props: {
    open: {
      type: Boolean
    },
    form: {
      type: Object
    },
    title: {
      type: String
    },
    btnLabel: {
      type: String,
      default: '新增'
    }
  },
  data() {
    const validatePublication = (rule, value, callback) => {
      if (value === undefined) {
        return callback(new Error('请填写刊指平台信息'))
      }

      if (value === '') {
        return callback(new Error('请填写刊指平台信息'))
      }

      if (value.length <= 0) {
        callback(new Error('请填写刊指平台信息'))
      }

      value.forEach(item => {
        if (item.publication_platform == undefined || item.publication_platform == '') {
          return callback(new Error('请填写刊指平台'))
        }
        if (item.publication_date == undefined || item.publication_date == '') {
          return callback(new Error('请填写刊指时间'))
        }

        if (item.publication_layout == undefined || item.publication_layout == '') {
          return callback(new Error('请填写刊指版面'))
        }
      })

      return callback()
    }
    return {
      platformList: [],
      printForm: {},
      // imageAction: '/imgapi/upload_file.php?tid=10918',
      imageAction: process.env.VUE_APP_BASE_API + '/newsDeclare/upload/file',
      authToken: this.$store.state.user.token,
      // fileList: [{ name: 'food.jpeg', url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100' }, { name: 'food2.jpeg', url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100' }],
      fileList: [],
      fileList1: [],
      dialog: false,
      content: '',
      editorConfig: {
        // 编辑器后端服务接口，参考后端规范 https://open-doc.modstart.com/ueditor-plus/backend.html
        serverUrl: 'https://img.qekj.net/php/controller.php',
        // 配置 UEditorPlus 的静态资源根路径，可以是 CDN 的静态资源地址
        UEDITOR_HOME_URL: '/UEditor/',
        // UEDITOR_CORS_URL: '/static/UEditorPlus'
        // 初始容器高度
        initialFrameHeight: 240,
        // 初始容器宽度
        initialFrameWidth: '100%',
        zIndex: 3000
      },
      active: 1,
      printOpen1: true,
      rules: {
        news_title: [
          { required: true, message: '新闻标题 必须填写', trigger: 'blur' }
        ],
        genre: [
          { required: true, message: '新闻体裁 必须填写', trigger: 'blur' }
        ],
        publication_json: [
          { required: true, message: '新闻刊指平台 必须填写', trigger: 'blur', validator: validatePublication }
        ],
        author_name: [
          { required: true, message: '作者姓名 必须填写', trigger: 'blur' }
        ],
        byline_order: [
          { required: true, message: '署名排序 必须填写', trigger: 'blur' }
        ],
        work_summary: [
          { required: true, message: '作品介绍 必须填写', trigger: 'blur' }
        ],
        reporter: [
          { required: true, message: '填报人 必须填写', trigger: 'blur' }
        ],
        reporter_phone: [
          { required: true, message: '填报人手机号 必须填写', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    pervBtnName() {
      let name = ''
      if (this.active == 2 || this.active == 3) {
        name = '上一步'
      }

      return name
    },
    nextBtnName() {
      let name = ''
      if (this.active == 1) {
        name = '下一步'
      } else if (this.active == 2) {
        name = '已打印、去上传'
      }

      return name
    }
  },
  created() {
    this.getPlatformList()
  },
  methods: {
    prev() {
      if (this.active-- < 1) this.active = 0
    },
    next() {
      if (this.active++ > 2) this.active = 0
    },
    submitForm(tableName, checkBack = false) {
      const formData = this.form
      this.$refs[tableName].validate((valid) => {
        if (valid) {
          const _filelist = []
          this.fileList.forEach(item => {
            _filelist.push({
              file_name: item.name,
              file_fullurl: item.url
            })
          })

          formData.attachments = _filelist

          const _filelist1 = []
          if (checkBack) { // 校验回传文件
            if (this.fileList1 == undefined || this.fileList1.length <= 0) {
              this.$message({
                message: '请上传盖章后表格',
                type: 'warning'
              })
              return
            }

            this.fileList1.forEach(item => {
              _filelist1.push({
                file_name: item.name,
                file_fullurl: item.url
              })
            })

            formData.back_attachments = _filelist1
          }

          if (this.btnLabel == '新增') {
            newsDeclareAdd(formData).then(res => {
              if (res.code == 10000) {
                this.$message({
                  message: '添加成功',
                  type: 'success'
                })
                // this.$emit('update:open', false)
                // this.$emit('refresh')
                // this.$parent.getList()
              }
              this.$emit('update-form', res.data)
              this.printForm = res.data
              this.active++
            })
          } else {
            newsDeclareUpdate(formData).then(res => {
              if (res.code == 10000) {
                if (this.active == 3) { // 申报
                  this.$message({ message: '申报成功', type: 'success' })
                  this.active = 1
                  this.$emit('update:open', false)
                  this.$emit('refresh')
                  this.$parent.getList()
                } else {
                  this.$message({
                    message: '修改成功',
                    type: 'success'
                  })
                  console.log(this.form.news_title)
                  this.$emit('update-form', this.form)
                  this.printForm = formData
                  this.active++
                }
                // this.$emit('update:open', false)
                // this.$emit('refresh')
                // this.$parent.getList()
              }
            })
          }
        } else {
          return false
        }
      })
    },
    delPublication(index) {
      this.form.publication_json.splice(index, 1) // 删除下标为1的元素
    },
    // 添加刊指平台
    addPublication() {
      console.log(this.form.publication_json)
      if (undefined == this.form.publication_json) {
        this.$set(this.form, 'publication_json', [{}])
      } else {
        this.form.publication_json.push({})
      }
    },
    beforeUpload(file) {
      let isLtSize = false
      isLtSize = file.size / 1024 / 1024 < 5
      if (!isLtSize) {
        this.$message.error('最大支持 5MB!')
      }
      return isLtSize
    },
    handleSuccess1(response, file, fileList) {
      if (response.code != 10000) {
        this.$notify.error({
          title: '错误',
          message: response.message
        })
      } else {
        const list = {
          name: file.name,
          url: response.data
        }
        this.fileList1.push(list)
      }
    },
    handleSuccess(response, file, fileList) {
      console.log(response, file)
      if (response.code != 10000) {
        this.$notify.error({
          title: '错误',
          message: response.message
        })
      } else {
        const list = {
          name: file.name,
          url: response.data
        }
        this.fileList.push(list)
      }
    },
    submitUpload() {
      this.$refs.upload.submit()
    },
    handleRemove(file, fileList) {
      console.log(file, fileList)
    },
    handlePreview(file) {
      console.log(file)
    },
    uploadFunc() {
    },
    close() {
      this.$emit('update:open', false)
      this.$parent.getList()
      this.$emit('update-form', {})
      this.active = 1
    },
    getPlatformList() {
      const that = this
      platformList({
        page: 1,
        limit: 9999
      }).then(response => {
        if (response.code === 10000) {
          that.platformList = response.data
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
/deep/ .ins-dialog{
  .el-dialog__body{
    padding-top: 10px;
  }
}
</style>
